package com.winning.pmph.schedule;

import java.util.ArrayList;
import java.util.List;

import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.winning.pmph.entity.IncreaseResource;


@Component
public class QuartzManager {
	@Autowired
	private Scheduler scheduler;

	private final String group = "task_group";

	public void addJob(IncreaseResource IncreaseResource) {
		try {
			JobDetail jobDetail = JobBuilder.newJob(IncreaseVideoJob.class).withIdentity(IncreaseResource.getId(), group)
					.build();
			SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity(IncreaseResource.getId(), group)
					.startAt(DateBuilder.futureDate(5, IntervalUnit.SECOND))
					.withSchedule(SimpleScheduleBuilder.simpleSchedule()).build();
			// 把作业和触发器注册到任务调度中
			scheduler.scheduleJob(jobDetail,trigger);
			// 启动
			if (!scheduler.isShutdown()) {
				scheduler.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<IncreaseResource> getRunningJob() throws SchedulerException {
		List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
		List<IncreaseResource> jobList = new ArrayList<IncreaseResource>(executingJobs.size());
		for (JobExecutionContext executingJob : executingJobs) {
			IncreaseResource job = new IncreaseResource();
			JobDetail jobDetail = executingJob.getJobDetail();
			JobKey jobKey = jobDetail.getKey();
			Trigger trigger = executingJob.getTrigger();
			job.setId(jobKey.getName());
			Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
			job.setName(triggerState.name());
			jobList.add(job);
		}
		return jobList;
	}

	public void pauseJob(IncreaseResource task) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(task.getId(), group);
		scheduler.pauseJob(jobKey);
	}

	public void deleteJob(IncreaseResource task) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(task.getId(), group);
		scheduler.deleteJob(jobKey);
	}
}
